<template>
	<view class="container">
		<!-- 顶部标题和刷新时间 -->
		<view class="header">
			<text v-if="formattedRefreshTime" class="refresh-time">最后更新: {{formattedRefreshTime}}</text>
		</view>
		<!-- 顶部搜索栏 + 功能按钮 -->
		<view class="top-bar">
			<view class="search-wrapper">
				<image src="/static/search-icon.png" class="search-icon" mode="aspectFit"></image>
				<input 
					v-model="searchKeyword" 
					class="search-input" 
					placeholder="搜索订单号/商品名称" 
					placeholder-class="search-placeholder"
					@input="handleSearch"
				/>
				<text v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</text>
			</view>
			<view class="top-buttons">
				<image src="/static/filter-icon.png" class="top-icon" mode="aspectFit" @click="showFilter = !showFilter"></image>
				<image src="/static/bill-icon.png" class="top-icon" mode="aspectFit" @click="gotoBill"></image>
			</view>
		</view>

		<!-- 订单分类标签 -->
		<scroll-view class="tag-scroll" scroll-x="true" :show-scrollbar="false">
			<view 
				v-for="(tag, index) in orderTags" 
				:key="index"
				class="order-tag"
				:class="{ active: currentTag === tag.value }"
				@click="switchTag(tag.value)"
			>
				{{ tag.label }}
			</view>
		</scroll-view>

		
		
		<!-- 加载中状态 -->
		<view v-if="loading" class="loading-container">
			<image src="../../static/loading.gif" class="loading-icon"></image>
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 有数据时显示（筛选后列表） -->
		<view v-else-if="loaded && filteredOrders.length > 0" class="order-list">
			<view v-for="(order, index) in filteredOrders" :key="order.orderNo || index" 
				class="order-item" @click="onOrderItemClicked(order.orderNo)">
				
				<!-- 订单头部信息 -->
				<view class="order-header">
					<view class="merchant-info">
						<image src="/static/logo.png" class="merchant-icon"></image>
						<text class="order-merchant">{{order.machineName || '自动售货机'}}</text>
					</view>
					<text class="order-status" :class="'status-' + getStatusClass(order.orderStatus)">
						{{order.orderStatus || '未知状态'}}
					</text>
				</view>
				
				<!-- 订单商品信息 -->
				<view class="order-product">
					<image :src="order.imageUrl" class="product-image" 
						@error="onImageError(order)" mode="aspectFill"></image>
					<view class="product-info">
						<text class="product-name">{{order.productName || '商品'}}</text>
					</view>
					<view class="arrow-icon">›</view>
				</view>
				
				<!-- 订单详细信息 -->
				<view class="order-details">
					<view class="detail-row">
						<text class="detail-label">订单号:</text>
						<text class="detail-value">{{order.orderNo || '-'}}</text>
					</view>
					<view class="detail-row">
						<text class="detail-label">创建时间:</text>
						<text class="detail-value">{{order.createTime || '-'}}</text>
					</view>
					<!-- 新增：总价移到创建时间下方 -->
					<view class="detail-row">
						<text class="detail-label">订单总价:</text>
						<text class="detail-value total-price">¥{{formatAmount(order.amount)}}</text>
					</view>
					<!-- 状态信息组 -->
					<view class="status-group">
						<view v-if="order.payStatus" class="status-tag" 
							:class="order.payStatus === '1' ? 'status-paid' : 'status-unpaid'">
							{{order.payStatus === '1' ? '已支付' : '未支付'}}
						</view>
						<view v-if="order.outStatus" class="status-tag"
							:class="order.outStatus === '1' ? 'status-shipped' : 'status-pending'">
							{{order.outStatus === '1' ? '已出货' : '未出货'}}
						</view>
					</view>
					
					<!-- 显示出货时间（如果有） -->
					<view v-if="order.outTime" class="detail-row">
						<text class="detail-label">出货时间:</text>
						<text class="detail-value">{{order.outTime}}</text>
					</view>
				</view>
			</view>
			
			<!-- 底部刷新提示 -->
			<view class="refresh-tip">
				<text class="tip-text">下拉可以刷新订单列表</text>
			</view>
		</view>

		<!-- 空状态（筛选后无数据） -->
		<view v-else-if="loaded && filteredOrders.length === 0" class="empty-container">
			<image src="/static/empty-order.png" mode="aspectFit" class="empty-icon"></image>
			<text class="empty-text">
				{{searchKeyword ? '未找到匹配的订单' : currentTag === 'all' ? '暂无订单数据' : '当前分类下无订单'}}
			</text>
			<button class="empty-button" @click="resetFilter()">
				{{searchKeyword ? '清除搜索' : '查看全部订单'}}
			</button>
		</view>

		<!-- 错误状态 -->
		<view v-else class="error-container">
			<image src="/static/error.png" mode="aspectFit" class="error-icon"></image>
			<text class="error-text">{{error || '加载订单列表失败'}}</text>
			<button class="error-button" @click="fetchOrderList()">重试</button>
		</view>
	</view>
</template>

<script> 
	import Order from '../../models/order' 
	let tag = "order-list" 
	export default { 
		onLoad() { 
			this.$log.info(tag, "onLoad") 
			this.fetchOrderList() 
		}, 
		data() { 
			return { 
				orders: [], // 原始订单列表
				searchKeyword: '', // 搜索关键词
				orderTags: [ // 分类标签配置
					{ label: '全部', value: 'all' },
					{ label: '待支付', value: 'pending_pay' },
					{ label: '待收货', value: 'pending_receive' },
					{ label: '已完成', value: 'completed' },
					{ label: '已取消', value: 'cancelled' }
				],
				currentTag: 'all', // 当前选中标签
				loading: false,
				loaded: false,
				error: "",
				formattedRefreshTime: "",
				default_path: "/static/error.png"
			} 
		}, 
		computed: {
			// 筛选后的订单列表（标签+搜索）
			filteredOrders() {
				let result = [...this.orders];
				
				// 1. 标签筛选
				switch(this.currentTag) {
					case 'pending_pay':
						result = result.filter(order => order.payStatus !== '1');
						break;
					case 'pending_receive':
						result = result.filter(order => order.payStatus === '1' && order.outStatus !== '1');
						break;
					case 'completed':
						result = result.filter(order => order.outStatus === '1');
						break;
					case 'cancelled':
						result = result.filter(order => order.orderStatus?.includes('已取消'));
						break;
					default:
						break;
				}
				
				// 2. 搜索筛选（订单号/商品名称）
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(order => 
						(order.orderNo?.toLowerCase().includes(keyword) || '') ||
						(order.productName?.toLowerCase().includes(keyword) || '')
					);
				}
				
				return result;
			}
		},
		methods: { 
			// 切换分类标签
			switchTag(tagValue) {
				this.currentTag = tagValue;
				this.$log.info(tag, `切换到标签: ${tagValue}`);
			},
			
			// 搜索处理
			handleSearch() {
				this.$log.info(tag, `搜索关键词: ${this.searchKeyword}`);
			},
			
			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
			},
			
			// 重置筛选（清空搜索+切回全部标签）
			resetFilter() {
				this.searchKeyword = '';
				this.currentTag = 'all';
			},
			
			// 跳转账单页面（示例）
			gotoBill() {
				uni.navigateTo({ url: '/pages/bill/bill' });
			},
			
			onOrderItemClicked(orderNo){ 
				this.$log.info(tag,`onOrderItemClicked ${orderNo}`) 
				uni.navigateTo({ 
					url:`/pages/order/order?orderNo=${orderNo}` 
				}) 
			}, 
			parseFromJsonArray(jsonArray){ 
				this.$log.info(tag,`parseFromJsonArray ${jsonArray.length}`) 
				let orders = [] 
				for(var i = jsonArray.length - 1;i>=0;i--){ 
					let orderJsonObject = jsonArray[i] 
					let order = new Order( 
						orderJsonObject.id,
						orderJsonObject.orderNo, 
						orderJsonObject.createTime, 
						orderJsonObject.status || orderJsonObject.orderStatus,
						orderJsonObject.amount || orderJsonObject.payAmount,
						orderJsonObject.productName, 
						orderJsonObject.productCover,
						orderJsonObject.orderStatus, 
						orderJsonObject.payAmount 
					)
					// 添加 imageUrl 属性用于模板显示
					order.imageUrl = `${this.$constant.BASE_URL}${orderJsonObject.productCover}`;
					// 添加其他可能需要的属性
					order.payStatus = orderJsonObject.payStatus;
					order.outStatus = orderJsonObject.outStatus;
					order.outTime = orderJsonObject.outTime;
					orders.push(order);
				} 
				return orders; 
			}, 
			fetchOrderList(){ 
				this.$log.info(tag,"fetchOrderList") 
				this.loading = true;
				this.loaded = false;
				this.error = "";
				uni.request({ 
					url:`${this.$constant.BASE_URL}/api/order/list`, 
					method:'GET', 
					header:{ 
						"Authorization":this.$loginManager.getToken() 
					}, 
					success: (res) => { 
						this.loading = false;
						this.loaded = true;
						if(res.data.code==200){ 
							this.orders = this.parseFromJsonArray(res.data.rows) 
							this.$log.info(tag,`success parsed orders ${this.orders.length}`) 
							// 更新刷新时间
							const now = new Date();
							this.formattedRefreshTime = `${now.getHours()}:${String(now.getMinutes()).padStart(2, '0')}`;
						} else {
							this.error = res.data.msg || '获取订单列表失败';
						}
					}, 
					fail: (err) => { 
						this.loading = false;
						this.loaded = false;
						this.error = err.errMsg || '网络请求失败';
						this.$log.error(tag, err.errMsg) 
					} 
				}) 
			},
			
			// 图片加载失败处理
			onImageError(order) {
				this.$log.info(tag, "图片加载失败，使用默认图片");
				order.imageUrl = this.default_path;
			},
			
			// 格式化金额
			formatAmount(amount) {
				if (!amount) return '¥0.00';
				return `¥${parseFloat(amount).toFixed(2)}`;
			},
			
			// 获取订单状态样式类
			getStatusClass(status) {
				if (!status) return 'unknown';
				if (status.includes('完成') || status.includes('已完成')) return 'completed';
				if (status.includes('支付') || status.includes('已支付')) return 'processing';
				if (status.includes('待')) return 'pending';
				if (status.includes('取消')) return 'cancelled';
				return 'unknown';
			}
			
		} 
	} 
</script>

<style>
	.container {
		padding: 0 30rpx 30rpx 30rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	/* 顶部搜索栏 */
	.top-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		background-color: #fff;
		margin: 0 -30rpx 20rpx -30rpx;
		padding: 20rpx 30rpx;
	}
	.search-wrapper {
		flex: 1;
		display: flex;
		align-items: center;
		background-color: #f5f5f5;
		border-radius: 40rpx;
		padding: 12rpx 20rpx;
	}
	.search-icon {
		width: 36rpx;
		height: 36rpx;
		margin-right: 12rpx;
	}
	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}
	.search-placeholder {
		color: #999;
	}
	.clear-btn {
		font-size: 32rpx;
		color: #999;
		margin-left: 12rpx;
	}
	.top-buttons {
		display: flex;
		align-items: center;
		margin-left: 20rpx;
	}
	.top-icon {
		width: 44rpx;
		height: 44rpx;
		margin-left: 24rpx;
	}
	
	/* 分类标签栏 */
	.tag-scroll {
		white-space: nowrap;
		background-color: #fff;
		margin: 0 -30rpx 20rpx -30rpx;
		padding: 16rpx 30rpx;
	}
	.order-tag {
		display: inline-block;
		font-size: 28rpx;
		padding: 12rpx 24rpx;
		margin-right: 16rpx;
		border-radius: 24rpx;
		background-color: #f5f5f5;
		color: #666;
	}
	.order-tag.active {
		background-color: #1989fa;
		color: #fff;
	}
	
	/* 头部样式 */
	.header {
		/* padding: 40rpx 0; */
		text-align: center;
		background-color: #fff;
		/* margin-bottom: 20rpx; */
		border-bottom: 1px solid #eee;
		position: sticky;
		top: 0;
		z-index: 10;
	}
	.title {
		font-size: 44rpx;
		font-weight: bold;
		color: #333;
		display: block;
		text-align: center;
	}
	.refresh-time {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
		display: block;
	}
	
	/* 加载中状态 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 400rpx;
		padding-top: 100rpx;
	}
	.loading-icon {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 20rpx;
	}
	.loading-text {
		font-size: 28rpx;
		color: #666;
	}
	
	/* 订单列表容器 */
	.order-list {
		margin-bottom: 20rpx;
	}
	
	/* 订单卡片样式 */
	.order-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	/* 订单头部信息 */
	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 24rpx;
		border-bottom: 1px solid #f5f5f5;
	}
	.merchant-info {
		display: flex;
		align-items: center;
	}
	.merchant-icon {
		width: 32rpx;
		height: 32rpx;
		border-radius: 6rpx;
		margin-right: 12rpx;
	}
	.order-merchant {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}
	.order-status {
		font-size: 24rpx;
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		font-weight: 500;
	}
	.status-completed {
		background-color: #f0f9ff;
		color: #07c160;
		border: 1px solid #07c160;
	}
	.status-processing {
		background-color: #e6f7ff;
		color: #1989fa;
		border: 1px solid #1989fa;
	}
	.status-pending {
		background-color: #fff7e6;
		color: #ff976a;
		border: 1px solid #ff976a;
	}
	.status-cancelled {
		background-color: #f5f5f5;
		color: #999;
		border: 1px solid #ddd;
	}
	.status-unknown {
		background-color: #f5f5f5;
		color: #999;
		border: 1px solid #ddd;
	}
	
	/* 商品信息 */
	.order-product {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 24rpx;
		border-bottom: 1px solid #f5f5f5;
		position: relative;
	}
	.product-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		background-color: #f5f5f5;
		margin-right: 24rpx;
		flex-shrink: 0;
	}
	.product-info {
		flex: 1;
		min-width: 0;
	}
	.product-name {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 12rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-weight: 500;
	}
	.product-amount {
		font-size: 36rpx;
		color: #e64340;
		font-weight: bold;
	}
	.arrow-icon {
		font-size: 40rpx;
		color: #ccc;
		font-weight: bold;
		margin-left: 20rpx;
	}
	
	/* 订单详情 */
	.order-details {
		padding-top: 10rpx;
	}
	.detail-row {
		display: flex;
		justify-content: space-between;
		margin-bottom: 16rpx;
	}
	.detail-label {
		font-size: 28rpx;
		color: #666;
		flex-shrink: 0;
	}
	.detail-value {
		font-size: 28rpx;
		color: #333;
		text-align: right;
		flex: 1;
		margin-left: 20rpx;
		word-break: break-all;
	}
	.total-price {
		font-size: 32rpx;
		color: #ff6b6b;
		font-weight: bold;
	}
	
	/* 状态标签组 */
	.status-group {
		display: flex;
		gap: 12rpx;
		margin: 20rpx 0;
		flex-wrap: wrap;
	}
	.status-tag {
		font-size: 22rpx;
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
		font-weight: 500;
	}
	.status-paid {
		background-color: #f0f9ff;
		color: #07c160;
		border: 1px solid #07c160;
	}
	.status-unpaid {
		background-color: #fff7e6;
		color: #ff976a;
		border: 1px solid #ff976a;
	}
	.status-shipped {
		background-color: #f0f9ff;
		color: #1989fa;
		border: 1px solid #1989fa;
	}
	.status-pending {
		background-color: #fff7e6;
		color: #ff976a;
		border: 1px solid #ff976a;
	}
	
	/* 刷新提示 */
	.refresh-tip {
		text-align: center;
		padding: 30rpx 0;
	}
	.tip-text {
		font-size: 24rpx;
		color: #999;
	}
	
	/* 空状态 */
	.empty-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 500rpx;
		padding-top: 100rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin-top: 30rpx;
	}
	.empty-icon {
		width: 160rpx;
		height: 160rpx;
		margin-bottom: 20rpx;
		opacity: 0.5;
	}
	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 30rpx;
	}
	.empty-button {
		background-color: #1989fa;
		color: #fff;
		font-size: 28rpx;
		padding: 15rpx 60rpx;
		height: 80rpx;
		line-height: 50rpx;
		border-radius: 40rpx;
		border: none;
	}
	
	/* 错误状态 */
	.error-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 500rpx;
		padding-top: 100rpx;
		background-color: #fff;
		border-radius: 16rpx;
		margin-top: 30rpx;
	}
	.error-icon {
		width: 160rpx;
		height: 160rpx;
		margin-bottom: 20rpx;
		opacity: 0.5;
	}
	.error-text {
		font-size: 28rpx;
		color: #ff4757;
		margin-bottom: 30rpx;
		text-align: center;
		padding: 0 40rpx;
	}
	.error-button {
		background-color: #1989fa;
		color: #fff;
		font-size: 28rpx;
		padding: 15rpx 60rpx;
		height: 80rpx;
		line-height: 50rpx;
		border-radius: 40rpx;
		border: none;
	}
	
	/* 响应式适配 */
	@media (max-width: 375px) {
		.container {
			padding: 0 20rpx 20rpx 20rpx;
		}
		.order-item {
			padding: 24rpx;
		}
		.product-image {
			width: 100rpx;
			height: 100rpx;
		}
	}
</style>